AddCSLuaFile( "autorun/auto.lua" )
AddCSLuaFile( "admin_menu.lua" )
AddCSLuaFile( "scoreboard_menu.lua" )
AddCSLuaFile( "SBoard.lua" )
AddCSLuaFile( "shared.lua" )
AddCSLuaFile( "inventory_client.lua" )
AddCSLuaFile( "NoticeEditor.lua" )
AddCSLuaFile( "ScrollingNotice.lua" )
AddCSLuaFile( "TransactionMenu.lua" )
AddCSLuaFile( "MapMenu.lua" )
AddCSLuaFile( "AntiNC.lua" )
AddCSLuaFile( "entities/ANCEntity/shared.lua" )

include( "shared.lua" )
include( "inventory_shared.lua" )
//include( "inventory_server.lua" )
require( "glon" )
require( "datastream" )
require( "mysql" )

LogTable = { }
NumLog = -1
Rocketing = false
TempTime = { }
ModCLEVEL = 6
AdminCLEVEL = 7
OwnerCLEVEL = 8
DB = 0
BanDB = 0
ERR = ""
NotNum = 1

JAILSTABLE = {}


//Add the following commands: SetPoints, and others to come. RCON SUPPORT needs to be added as well
//BIGTODO - Create the "Inventory" system for use with the points. Able to buy abilities and items with
//points. Make this a separate file similar to the PointsANDTime file, OR include it in said file. (Probably the latter)

// ADD GIVEPOINTS command or interface

//Add the basic commands Ban, Kick (Maybe time based versions of both), SavePlayerData() command,,
//and others similar to these.	NOTICES - Add this command

//Move the time and points system over to the server for ease of use
//Make the inventory replace the script used for old time and points

//BIGTODO: Add the Ban Database and fix the command as it. Check for a banned player on Either Connect or Spawn. Whichever works.

//Work on more commands, then start PP TELEPORTING and chat commands of the like

//Notices Commands

function Init_INFO()
	timer.Create( "SaveTimer", SaveInterval, 0, SavePlayerData )
	timer.Create( "TSys", 1, 0, TimeSys )
	
	DB, ERR = mysql.connect("127.0.0.1", "POAdmin", "119SHZH", "playerinfodb", 3307)
	if DB == 0 then print(ERR .. "\n") end
	if DB != 0 then print("MySQL Database Connection Successful!") end //DEBUGGING
	
	BanDB, ERR2 = mysql.connect("127.0.0.1", "POAdmin", "119SHZH", "bandb", 3307)
	if BanDB == 0 then print(ERR2 .. "\n") end
	if BanDB != 0 then print("MySQL Database Connection Number 2 Successful!") end //DEBUGGING
end
hook.Add( "Initialize", "Init_INFO", Init_INFO )

/*-------------------------------------------------------
DB Manipulation
*/-------------------------------------------------------

function DBINFO( ply ) //Let's use this for all future MySQL queries
	return mysql.query( DB, "SELECT * FROM PlayerINFO WHERE UID = '" .. ply:UniqueID() .. "'" )
end

function RANKDBINFO( ) //Let's use this for all future MySQL queries
	return mysql.query( DB, "SELECT * FROM RankTable")
end

function DBINSERT( ply, data )
	local TS = table.concat( data, "', '" )
	mysql.query( DB, "INSERT INTO PlayerINFO (UID, NAME, RANK, TIME, POINTS, FLAGS) VALUES ('" .. TS .. "')" )
end

function DBUPDATE( ply, data )
	local TS = table.concat( data, ", " )
	mysql.query( DB, "UPDATE PlayerINFO SET " .. TS .. " WHERE UID ='" .. ply:UniqueID() .. "'" )
end

function BanDBINFO( ply ) //Let's use this for all future MySQL queries
	return mysql.query( BanDB, "SELECT * FROM playerbans WHERE UID = '" .. ply:UniqueID() .. "'" )
end

function BanDBINSERT( ply, data )
	local TS = table.concat( data, "', '" )
	mysql.query( BanDB, "INSERT INTO playerbans (UID, NAME, REASON, UNBANTIME, IP, TIMEBANNED) VALUES ('" .. TS .. "')" )
end

function BanDBUPDATE( ply, data )
	local TS = table.concat( data, ", " )
	mysql.query( BanDB, "UPDATE playerbans SET " .. TS .. " WHERE UID ='" .. ply:UniqueID() .. "'" )
end

function BanDBDELETE( address, ply )
	if ply then
		mysql.query( BanDB, "DELETE FROM playerbans WHERE UID = '" .. ply:UniqueID() .. "'" )
	else
		mysql.query( BanDB, "DELETE FROM playerbans WHERE IP = '" .. address .. "'" )
	end
end

function SetNWs( ply, nwt )
	ply:SetNetworkedString( "UID", nwt[1] )
	ply:SetNetworkedString( "name", nwt[2] )
	ply:SetNetworkedString( "rank", nwt[3] )
	TempTime[ply:UniqueID()] = nwt[4]
	ply:SetNetworkedInt( "points", nwt[5] )
	ply:SetNetworkedString( "flags", nwt[6] )
	ply:SetNetworkedBool( "NoClip", true )
	ply:SetNWBool( "intrans", false )
	ply:SetNWInt( "jailed", -1 )
	
end

function FlagErrorMessage( PLYFLAG, TARGETFLAG, ply )
	if PLYFLAG == nil then
		ply:PrintMessage(HUD_PRINTTALK, "You lack the necessary flags for this command.")
	elseif PLYFLAG and TARGETFLAG then
		ply:PrintMessage(HUD_PRINTTALK, "Unable to perform this command on a player with the same flag as you.")
	end
end

/*-------------------------------------------------------
Commands
*/-------------------------------------------------------

function HurtPlayer( ply, command, args )
	local APLY = player.GetByUniqueID(args[1])
	local plyFlag = CheckFlags( ply, "M" )
	local APLYFlag = CheckFlags( APLY, "M" )
	
	if plyFlag and (APLYFlag == nil or APLY == ply) then
 
		if APLY:Health() <= tonumber(args[2]) then
			APLY:Kill()
			XQAM_LOG(ply, " killed ", APLY)
		else
			APLY:SetHealth(APLY:Health() - tonumber(args[2]))
			XQAM_LOG(ply, " inflicted " .. tonumber(args[2]) .. " damage to ", APLY)
			return APLY:Health()
		end
		
	else
		FlagErrorMessage( plyFlag, APLYFlag, ply )
	end
end
concommand.Add( "Hurt_Player", HurtPlayer )

function SetHealthOFPlayer( ply, command, args )
	local APLY = player.GetByUniqueID(args[1])
	local plyFlag = CheckFlags( ply, "M" )
	local APLYFlag = CheckFlags( APLY, "M" )
	
	if plyFlag and (APLYFlag == nil or APLY == ply) then
 
		if tonumber(args[2]) <= 0 then
			APLY:Kill()
			XQAM_LOG(ply, " killed ", APLY)
		else
			APLY:SetHealth(math.Clamp(tonumber(args[2]),0,10000))
			XQAM_LOG(ply, " set " .. math.Clamp(tonumber(args[2]),0,10000) .. " as the health of ", APLY)
			return APLY:Health()
		end
		
	else
		FlagErrorMessage( plyFlag, APLYFlag, ply )
	end
	
end
concommand.Add( "Set_Health", SetHealthOFPlayer )

function StripPlayerWeapons( ply, command, args )
	local APLY = player.GetByUniqueID(args[1])
	local plyFlag = CheckFlags( ply, "M" )
	local APLYFlag = CheckFlags( APLY, "M" )
	
	if plyFlag and (APLYFlag == nil or APLY == ply) then
		APLY:StripWeapons()
		XQAM_LOG(ply, " stripped the weapons of ", APLY)
	else
		FlagErrorMessage( plyFlag, APLYFlag, ply )
	end
end
concommand.Add( "Strip_Weapons", StripPlayerWeapons )

function ToggleGODPLAYER( ply, command, args )
	local APLY = player.GetByUniqueID(args[1])
	local plyFlag = CheckFlags( ply, "M" )
	local APLYFlag = CheckFlags( APLY, "M" )
	
	if plyFlag and (APLYFlag == nil or APLY == ply) then
	
		if(args[2] == "0") then
			APLY:GodDisable()
			XQAM_LOG(ply, " UnGodded ", APLY)
		elseif(args[2] == "1") then
			APLY:GodEnable()
			XQAM_LOG(ply, " Godded ", APLY)
		end
		
	else
		FlagErrorMessage( plyFlag, APLYFlag, ply )
	end
end
concommand.Add( "Toggle_Godmode", ToggleGODPLAYER )

function RocketExplode( ply, SMOKE, NCBool )
	local explosion = ents.Create( "env_explosion" )
	explosion:SetPos( ply:GetPos() )
	explosion:SetOwner( ply )
	explosion:Spawn()
	explosion:SetKeyValue( "iMagnitude", 500 )
	explosion:Fire( "Explode", 0, 0 )
	explosion:EmitSound( "weapon_AWP.Single", 400, 400 )
	SMOKE:Remove()
	ply:Kill()
	Rocketing = false
	ply:SetNetworkedBool( "NoClip", NCBool )
end

function RocketPlayer( ply, command, args )
	local APLY = player.GetByUniqueID(args[1])
	local plyFlag = CheckFlags( ply, "M" )
	local APLYFlag = CheckFlags( APLY, "M" )
	local OldNC = true
	
	if plyFlag and (APLYFlag == nil or APLY == ply) then
		if not Rocketing then
			if not APLY:Alive() then APLY:Spawn() end
			if APLY:InVehicle() then APLY:ExitVehicle() end
			if APLY:GetNetworkedBool( "NoClip" ) then 
				OldNC = true
				APLY:SetNetworkedBool( "NoClip", false )
				APLY:SetMoveType(MOVETYPE_WALK)
			else
				OldNC = false
			end
			APLY:SetLocalVelocity( Vector(0,0,2000))
			local smoke = util.SpriteTrail(APLY, 0, Color(255,0,0), false, 25, 1, 4, 1/(25+1)*0.5, "trails/smoke.vmt")
			timer.Create("RocketTimer", 2.5, 1, RocketExplode, APLY, smoke, OldNC)
			XQAM_LOG(ply, " Rocketed ", APLY)
			Rocketing = true
		end
	else
		FlagErrorMessage( plyFlag, APLYFlag, ply )
	end
end
concommand.Add( "Rocket_Player", RocketPlayer )

function SetPlayerRank( ply, command, args )
	local APLY = player.GetByUniqueID(args[1])
	local plyFlag = CheckFlags( ply, "O" )
	local APLYFlag = CheckFlags( APLY, "O" )

	if plyFlag and (APLYFlag == nil or APLY == ply) then
		PromotePlayer( ply, args[2], false, APLY )
	else
		FlagErrorMessage( plyFlag, APLYFlag, ply )
	end
end
concommand.Add( "Set_Rank", SetPlayerRank )

function AddPlayerHours( ply, command, args )
	local APLY = player.GetByUniqueID(args[1])
	local plyFlag = CheckFlags( ply, "O" )
	local APLYFlag = CheckFlags( APLY, "O" )
	
	if plyFlag and (APLYFlag == nil or APLY == ply) then
		TempTime[args[1]] = math.Clamp(TempTime[args[1]] + tonumber(args[2]), 0, 2000000000)
		DBUPDATE( APLY, { "TIME= " .. TempTime[args[1]] } )
		XQAM_LOG(ply, " added " .. (tonumber(args[2]) / 3600) .. " to the hours of ", APLY)
	else
		FlagErrorMessage( plyFlag, APLYFlag, ply )
	end	
end
concommand.Add( "Add_Hours", AddPlayerHours )

function AddPlayerFlags( ply, command, args )
	local APLY = player.GetByUniqueID(args[1])
	local plyFlag = CheckFlags( ply, "O" )
	local APLYFlag = CheckFlags( APLY, "O" )
	
	if plyFlag and (APLYFlag == nil or APLY == ply) then
		
		if string.find( APLY:GetNetworkedString( "flags" ) , args[2] ) == nil then
			APLY:SetNetworkedString( "flags", DBINFO( APLY )[1][7] .. "," .. args[2] )
			DBUPDATE( APLY, { "FLAGS= '" .. APLY:GetNetworkedString( "flags" ) .. "'" } )
			XQAM_LOG( ply, " gave the " .. args[2] .. " flag to ", APLY )
		elseif string.find( APLY:GetNetworkedString( "flags" ) , args[2] ) then
			ply:PrintMessage(HUD_PRINTTALK, "Target player already has the selected flag")
		end
		
	else
		FlagErrorMessage( plyFlag, APLYFlag, ply )
	end
end
concommand.Add( "Add_Player_Flags", AddPlayerFlags )

function RemovePlayerFlags( ply, command, args )
	local APLY = player.GetByUniqueID(args[1])
	local plyFlag = CheckFlags( ply, "O" )
	local APLYFlag = CheckFlags( APLY, "O" )
	
	if plyFlag and (APLYFlag == nil or APLY == ply) then
		
		if string.find( APLY:GetNetworkedString( "flags" ) , args[2] .. "," ) then
			APLY:SetNetworkedString( "flags", string.Replace( APLY:GetNetworkedString( "flags" ), args[2] .. ",", "" ) )
			DBUPDATE( APLY, { "FLAGS= '" .. APLY:GetNetworkedString( "flags" ) .. "'" } )
			XQAM_LOG( ply, " revoked the " .. args[2] .. " flag from ", APLY )
				if args[2] == "N" then APLY:SetMoveType(MOVETYPE_WALK) end
		elseif string.find( APLY:GetNetworkedString( "flags" ) , "," .. args[2] ) then
			APLY:SetNetworkedString( "flags", string.Replace( APLY:GetNetworkedString( "flags" ), "," .. args[2], "" ) )
			DBUPDATE( APLY, { "FLAGS= '" .. APLY:GetNetworkedString( "flags" ) .. "'" } )
			XQAM_LOG( ply, " revoked the " .. args[2] .. " flag from ", APLY )
				if args[2] == "N" then APLY:SetMoveType(MOVETYPE_WALK) end
		elseif string.match( APLY:GetNetworkedString( "flags" ) , args[2] ) == APLY:GetNetworkedString( "flags" ) then
			APLY:SetNetworkedString( "flags", string.Replace( APLY:GetNetworkedString( "flags" ), args[2], "" ) )
			DBUPDATE( APLY, { "FLAGS= '" .. APLY:GetNetworkedString( "flags" ) .. "'" } )
			XQAM_LOG( ply, " revoked the " .. args[2] .. " flag from ", APLY )
				if args[2] == "N" then APLY:SetMoveType(MOVETYPE_WALK) end
		elseif string.find( APLY:GetNetworkedString( "flags" ) , args[2] ) == nil then
			ply:PrintMessage(HUD_PRINTTALK, "Target player does not have the selected flag")
		end
		
	else
		FlagErrorMessage( plyFlag, APLYFlag, ply )
	end
end
concommand.Add( "Remove_Player_Flags", RemovePlayerFlags )

function TogglePlayerNoClip( ply, command, args )
	local APLY = player.GetByUniqueID(args[1])
	local plyFlag = CheckFlags( ply, "M" )
	local APLYFlag = CheckFlags( APLY, "M" )
	
	if plyFlag and (APLYFlag == nil or APLY == ply) then
		
		if args[2] == "1" and !APLY:GetNetworkedBool( "NoClip" ) then
			APLY:SetNetworkedBool( "NoClip", true )
			XQAM_LOG( ply, " allowed NoClip for ", APLY )
		elseif args[2] == "1" and APLY:GetNetworkedBool( "NoClip" ) then
			ply:PrintMessage(HUD_PRINTTALK, "The selected player's NoClip is already allowed" )
		elseif args[2] == "0" and APLY:GetNetworkedBool( "NoClip" ) then
			APLY:SetNetworkedBool( "NoClip", false )
			APLY:SetMoveType(MOVETYPE_WALK)
			XQAM_LOG( ply, " disallowed NoClip for ", APLY )
		elseif args[2] == "0" and !APLY:GetNetworkedBool( "NoClip" ) then
			APLY:PrintMessage(HUD_PRINTTALK, "The selected player's NoClip is already disallowed" )
		end
		
		
	else
		FlagErrorMessage( plyFlag, APLYFlag, ply )
	end
end
concommand.Add( "Toggle_Player_NoClip", TogglePlayerNoClip )

function KickPlayer( ply, command, args )
	local APLY = player.GetByUniqueID(args[1])
	local plyFlag = CheckFlags( ply, "M" )
	local APLYFlag = CheckFlags( APLY, "M" )
	local REASON = ""
	
	if plyFlag and (APLYFlag == nil or APLY == ply) then
		if args[2] then REASON = args[2]
		else REASON = "Blank Reason" end
		
		RunConsoleCommand( "kickid", APLY:UserID(), REASON )
		XQAM_LOG( ply, ply:Nick() .. " kicked " .. APLY:Nick() .. " with the reason: " .. REASON )
		
	else
		FlagErrorMessage( plyFlag, APLYFlag, ply )
	end
end
concommand.Add( "Kick_Player", KickPlayer )

function BanPlayer( ply, command, args )
	local APLY = player.GetByUniqueID(args[1])
	local plyFlag = CheckFlags( ply, "A" )
	local APLYFlag = CheckFlags( APLY, "A" )
	local REASON = "No Reason Specified"
	
	if plyFlag and (APLYFlag == nil or APLY == ply) then
		if args[3] then REASON = args[3] end
		local UBT = tonumber(os.time()) + tonumber(args[2])
		
		BanDBINSERT( APLY, { APLY:UniqueID(), APLY:Nick(), REASON, UBT, APLY:IPAddress(), tonumber(os.time()) } )
		RunConsoleCommand( "kickid", APLY:UserID(), REASON )
		XQAM_LOG( ply, ply:Nick() .. " banned " .. APLY:Nick() .. " with the reason: " .. REASON .. ", for " .. args[4] )
		
	else
		FlagErrorMessage( plyFlag, APLYFlag, ply )
	end
end
concommand.Add( "Ban_Player", BanPlayer )

function JailPlayer( ply, command, args )		//Make a check for jailed players to not use Teleport    block +menu   FIX THIS >.<
	local APLY = player.GetByUniqueID(args[1])
	local plyFlag = CheckFlags( ply, "M" )
	local APLYFlag = CheckFlags( APLY, "M" )
	
	if plyFlag and (APLYFlag == nil or APLY == ply) then
		local SPAWNNUM = 0
		
		local TDATA = {}
		TDATA.start = APLY:GetPos()
		TDATA.endpos = APLY:GetPos() - Vector( 0, 0, 16384 )
		TDATA.mask = 16395
		
		local JPOS = util.TraceLine( TDATA )
	
		local JSPAWN = ents.Create( "prop_physics" )
			JSPAWN:SetName( APLY:UniqueID() )
			JSPAWN:SetSolid(SOLID_NONE)
			JSPAWN:SetModel( "models/props_lab/huladoll.mdl" )
			JSPAWN:SetPos( JPOS.HitPos  + Vector( 0, 0, 10 ) )
			JSPAWN:Spawn()
			JSPAWN:Activate()
			
			local SPO = JSPAWN:GetPhysicsObject()
				SPO:EnableCollisions( false )
				SPO:EnableMotion( false )
			
			print( "JSPAWN NAME: " .. JSPAWN:GetName() )
			
		local JAILBARS = {}
		JAILBARS.PLAYER = APLY
			
		JAILBARS.F1 = ents.Create( "prop_physics" )
			JAILBARS.F1:SetModel( "models/props_c17/fence01b.mdl" )
			JAILBARS.F1:SetPos( JPOS.HitPos + Vector( 100, 0, 0 ) )
			JAILBARS.F1:SetMoveType( MOVETYPE_NONE )
			JAILBARS.F1:Spawn()
			JAILBARS.F1:Activate()
			
			local PO = JAILBARS.F1:GetPhysicsObject()
				PO:EnableMotion( false )
			
		JAILBARS.F2 = ents.Create( "prop_physics" )
			JAILBARS.F2:SetModel( "models/props_c17/fence01b.mdl" )
			JAILBARS.F2:SetPos( JPOS.HitPos + Vector( -100, 0, 0 ) )
			JAILBARS.F2:SetMoveType( MOVETYPE_NONE )
			JAILBARS.F2:Spawn()
			JAILBARS.F2:Activate()
			
			local PO2 = JAILBARS.F2:GetPhysicsObject()
				PO2:EnableMotion( false )
			
		JAILBARS.F3 = ents.Create( "prop_physics" )
			JAILBARS.F3:SetModel( "models/props_c17/fence01b.mdl" )
			JAILBARS.F3:SetPos( JPOS.HitPos + Vector( 0, 100, 0 ) )
			JAILBARS.F3:SetMoveType( MOVETYPE_NONE )
			JAILBARS.F3:Spawn()
			JAILBARS.F3:Activate()
			
			local PO3 = JAILBARS.F3:GetPhysicsObject()
				PO3:EnableMotion( false )

		JAILBARS.F4 = ents.Create( "prop_physics" )
			JAILBARS.F4:SetModel( "models/props_c17/fence01b.mdl" )
			JAILBARS.F4:SetPos( JPOS.HitPos + Vector( 0, -100, 0 ) )
			JAILBARS.F4:SetMoveType( MOVETYPE_NONE )
			JAILBARS.F4:Spawn()
			JAILBARS.F4:Activate()
			
			local PO4 = JAILBARS.F4:GetPhysicsObject()
				PO4:EnableMotion( false )
			
		JAILBARS.F5 = ents.Create( "prop_physics" )		//Work on angles here
			JAILBARS.F5:SetModel( "models/props_c17/fence01b.mdl" )
			JAILBARS.F5:SetPos( JPOS.HitPos + Vector( 0, 0, 100 ) )
			JAILBARS.F5:SetMoveType( MOVETYPE_NONE )
			JAILBARS.F5:Spawn()
			JAILBARS.F5:Activate()
			
			local PO5 = JAILBARS.F5:GetPhysicsObject()
				PO5:EnableMotion( false )
			
		table.insert( JAILSTABLE, JAILBARS )
			
		APLY:SetPos( JPOS.HitPos )
		APLY:SetNWInt( "jailed", 1 )
		APLY:SetNetworkedBool( "NoClip", false )	//Make sure to set them their movetype here as well.
		APLY:StripWeapons()
		
		XQAM_LOG( ply, ply:Nick() .. " jailed " .. APLY:Nick() )
		
	else
		FlagErrorMessage( plyFlag, APLYFlag, ply )
	end
end
concommand.Add( "Jail_Player", JailPlayer )

function UnjailPlayer( ply, command, args )		//Make a check for jailed players to not use Teleport
	local APLY = player.GetByUniqueID(args[1])
	local plyFlag = CheckFlags( ply, "M" )
	local APLYFlag = CheckFlags( APLY, "M" )
	
	if plyFlag and (APLYFlag == nil or APLY == ply) then
		for k,v in pairs( JAILSTABLE ) do
			if v.PLAYER == APLY then
				v.F1:Remove()
				v.F2:Remove()
				v.F3:Remove()
				v.F4:Remove()
				v.F5:Remove()
				
				table.remove( JAILSTABLE, k )
			break end
		end
		
		local ESPAWN = ents.FindByName( APLY:UniqueID() )
			ESPAWN:Remove()
		
		APLY:SetNWInt( "jailed", -1 )
		APLY:SetNetworkedBool( "NoClip", true )
		
		XQAM_LOG( ply, ply:Nick() .. " unjailed " .. APLY:Nick() )
	else
		FlagErrorMessage( plyFlag, APLYFlag, ply )
	end
end
concommand.Add( "Unjail_Player", UnjailPlayer )

function JailPlayerSpawn( ply )
	print( ply:GetNWInt( "jailed" ) )

	if ply:GetNWInt( "jailed" ) != -1 then
		print( "WEAPONS STRIPPED" )
		ply:StripWeapons()
		ply:SetPos( ents.FindByName( ply:UniqueID() ):GetPos() )
	end

end
hook.Add( "PlayerSpawn", "JailPlayerSpawn", JailPlayerSpawn )

function AddPoints( ply, command, args )
	local APLY = player.GetByUniqueID(args[1])
	local plyFlag = CheckFlags( ply, "O" )
	local APLYFlag = CheckFlags( APLY, "O" )
	
	if plyFlag and (APLYFlag == nil or APLY == ply) then
		APLY:SetNetworkedInt( "points", math.Clamp(APLY:GetNetworkedInt( "points" ) + tonumber(args[2]),0,2000000000) )
		DBUPDATE( APLY, { "POINTS= " .. APLY:GetNetworkedInt( "points" ) } )
		XQAM_LOG( ply, ply:Nick() .. " modified " .. APLY:Nick() .. "'s points by " .. args[2] )
	else
		FlagErrorMessage( plyFlag, APLYFlag, ply )
	end
end
concommand.Add( "Add_Points", AddPoints )

function TeleportToTarget( ply, command, args )
	local APLY = player.GetByUniqueID(args[1])
	local plyFlag = CheckFlags( ply, "T" )
	local APLYFlag = CheckFlags( APLY, "T" )
	
	if plyFlag and (APLYFlag == nil or APLY == ply) then
		local TR = APLY:GetEyeTraceNoCursor()
		APLY:SetPos( TR.HitPos + (TR.HitNormal * 10) )
		for k,v in pairs(player.GetAll()) do
			v:PrintMessage(HUD_PRINTTALK, APLY:Nick() .. " teleported")
		end
	else
		FlagErrorMessage( plyFlag, APLYFlag, ply )
	end
end
concommand.Add( "tp", TeleportToTarget )

function SendTRequest( ply, target, action )
	local rp = RecipientFilter()
	rp:AddPlayer( target )
	
	umsg.Start( "TRequest", rp )
		umsg.Entity( ply )
		umsg.String( action )
	umsg.End()
end

function TeleportToPlayer( ply, command, args )
	local APLY = player.GetByUniqueID(args[1])
	local plyFlag = CheckFlags( ply, "T" )
	local APLYFlag = CheckFlags( APLY, "T" )
	
	if plyFlag then
		ply:PrintMessage( HUD_PRINTTALK, "You have sent " .. APLY:Nick() .. " a teleport request" )
		SendTRequest( ply, APLY, "teleport to you" )
	else
		FlagErrorMessage( plyFlag, APLYFlag, ply )
	end
end
concommand.Add( "goto", TeleportToPlayer )

function BringToPlayer( ply, command, args )
	local APLY = player.GetByUniqueID(args[1])
	local HasReq = args[2]
	local plyFlag = CheckFlags( ply, "T" )
	local APLYFlag = CheckFlags( APLY, "T" )
	
	if plyFlag then
		ply:PrintMessage( HUD_PRINTTALK, "You have sent " .. APLY:Nick() .. " a teleport request" )
		SendTRequest( ply, APLY, "teleport you to them" )
	else
		FlagErrorMessage( plyFlag, APLYFlag, ply )
	end
end
concommand.Add( "bring", BringToPlayer )

function AcceptRequest( ply, command, args )
	local Sender = player.GetByUniqueID(args[1])
	Sender:PrintMessage( HUD_PRINTTALK, ply:Nick() .. " has accepted your teleport request." )
	
	if args[2] == "teleport to you" then
		Sender:SetPos( ply:GetPos() + Vector( 0, 0, 100 )  )
		for k,v in pairs(player.GetAll()) do
			v:PrintMessage(HUD_PRINTTALK, Sender:Nick() .. " was teleported to " .. ply:Nick() )
		end
	elseif args[2] == "teleport you to them" then
		ply:SetPos( Sender:GetPos() + Vector( 0, 0, 100 )  )
		for k,v in pairs(player.GetAll()) do
			v:PrintMessage(HUD_PRINTTALK, ply:Nick() .. " was teleported to " .. Sender:Nick() )
		end
	end
end
concommand.Add( "AcceptTeleportRequest", AcceptRequest )

function RejectRequest( ply, command, args )
	local Sender = player.GetByUniqueID(args[1])
	Sender:PrintMessage( HUD_PRINTTALK, ply:Nick() .. " has rejected your teleport request." )
end
concommand.Add( "RejectTeleportRequest", RejectRequest )

function HasRequest( ply, command, args )
	local Sender = player.GetByUniqueID(args[1])
	
	Sender:PrintMessage( HUD_PRINTTALK, ply:Nick() .. " already has a request" )
end
concommand.Add( "HasRequest", HasRequest )

function CommandRebuildTables( ply, command, args )
	local plyFlag = CheckFlags( ply, "O" )
	
	if plyFlag then
		RebuildStoreTables( ply )
		XQAM_LOG( ply, ply:Nick() .. " rebuilt the store's tables" )
	else
		FlagErrorMessage( plyFlag, APLYFlag, ply )
	end
end
concommand.Add( "Rebuild_Store_Tables", CommandRebuildTables )

/*-------------------------------------------------------
End of Commands
*/-------------------------------------------------------


/*-------------------------------------------------------
Transactions
*/-------------------------------------------------------
function PointTransaction( ply, command, args )
	local APLY = player.GetByUniqueID(args[1])
	local CLAMP = math.Clamp( tonumber(args[2]), 0, ply:GetNetworkedInt( "points" ) )

	APLY:SetNetworkedInt( "points", APLY:GetNetworkedInt( "points" ) + CLAMP )
	APLY:SetNWBool( "intrans", false )
	APLY:PrintMessage( HUD_PRINTCENTER, ply:Nick() .. " has traded you " .. CLAMP .. " points." )
	DBUPDATE( APLY, { "POINTS= " .. APLY:GetNetworkedInt( "points" ) } )
	
	ply:SetNetworkedInt( "points", ply:GetNetworkedInt( "points" ) - CLAMP )
	ply:SetNWBool( "intrans", false )
	ply:PrintMessage( HUD_PRINTCENTER, "You have traded " .. CLAMP .. " points to " .. APLY:Nick() .. "." )
	DBUPDATE( ply, { "POINTS= " .. ply:GetNetworkedInt( "points" ) } )
end
concommand.Add( "PointTransaction", PointTransaction )

function CheckStartTransaction( ply, key )
	local ent = ply:GetEyeTraceNoCursor().Entity

	if key == IN_USE then
	
		if ent and ent:IsValid() and ent:IsPlayer() and ply:GetPos():Distance( ent:GetPos() ) <= 75 then
			print( "PLAYER USED" )
			if !ent:GetNWBool( "intrans" ) and !ply:GetNWBool( "intrans" ) then
				local rp = RecipientFilter()
				rp:AddPlayer( ply )
				
				umsg.Start( "PlayerUseMESS", rp )
					umsg.String( ent:UniqueID() )
				umsg.End()
				ply:SetNWBool( "intrans", true )
				
				ent:PrintMessage( HUD_PRINTCENTER, ply:Nick() .. " has began a transaction with you." )
			elseif ply:GetNWBool( "intrans" ) then
				ply:PrintMessage( HUD_PRINTCENTER, "You are already in a transaction." )
			elseif ent:GetNWBool( "intrans" ) then
				ply:PrintMessage( HUD_PRINTCENTER, "Selected player is already in a transaction." )
			end
		end
		
	end

end
hook.Add( "KeyPress", "CheckStartTransaction", CheckStartTransaction )

function FinishTransaction( ply, command, args )

	ply:SetNWBool( "intrans", false )

end
concommand.Add( "FinishTransaction", FinishTransaction )
/*-------------------------------------------------------
End of Transactions
*/-------------------------------------------------------

/*-------------------------------------------------------
Anti NoClip
*/-------------------------------------------------------
function CheckAntiNC( ply, key )
	local ent = ply:GetEyeTraceNoCursor().Entity

	if key == IN_USE then
	
		if( ent and ent:IsValid() and ent:GetClass() == "prop_physics" ) then
			
			local rp = RecipientFilter()
			rp:AddPlayer( ply )
				
			umsg.Start( "PlayerANCMESS", rp )
				umsg.Entity( ent )
				umsg.String( ply:GetNWString( "rank" ) )
			umsg.End()
		end
	
	end
	
end
hook.Add( "KeyPress", "CheckAntiNC", CheckAntiNC )
/*-------------------------------------------------------
End of Anti NoClip
*/-------------------------------------------------------

/*-------------------------------------------------------
Time and Points system
*/-------------------------------------------------------
function TimeSys() //Add the points system in the same way later on --Scrap that, let's add it in this function

	for k,v in pairs( player.GetAll() ) do
		local PT = 0
		local RI = 0
		
		TempTime[v:UniqueID()] = TempTime[v:UniqueID()] + 1
		if math.fmod( TempTime[v:UniqueID()], PointInterval) == 0 then
			v:SetNetworkedInt( "points", v:GetNetworkedInt( "points" ) + 1 )
			v:PrintMessage( HUD_PRINTTALK, "You have just gained a point!\nYour point total is now " .. v:GetNetworkedInt( "points" ) )
			v:SendLua( "surface.PlaySound( \"common/bugreporter_succeeded.wav\" )" )
		end
		
		for n,r in pairs( RankTable ) do
			if v:GetNetworkedString( "rank" ) == r then
				PT = tonumber(TimesTable[n + 1])
				RI = n
			end
		end
		
		if v:IsValid() and PT != -1 and TempTime[v:UniqueID()] >= PT then
			PromotePlayer( v, RankTable[RI + 1], true )
		end
		
	end
	
	if math.floor( math.fmod( CurTime(), NoticeInterval ) ) == 0 then
		SendNotice( ReadNotices[NotNum] )
		print( ReadNotices[NotNum] )
		NotNum = NotNum + 1
		if NotNum > table.getn( ReadNotices ) then NotNum = 1 end
	end
	
end

function SendNotice( NOTICE )
	local rp = RecipientFilter()
	rp:AddAllPlayers()
	
	umsg.Start( "NoticeMSG", rp)
		umsg.String( NOTICE )
	umsg.End()

end

function PromotePlayer( ply, optrank, auto, APLY ) //Add a Flags log here.
local RI = -1
for k,v in pairs( RankTable ) do
	if optrank == v then RI = k end
end

	if optrank and auto then
		ply:SetNetworkedString( "rank", optrank )
		
		if RI >= tonumber(RankNums["Member"]) and string.find( ply:GetNetworkedString( "flags" ), "T" ) == nil then
			ply:SetNetworkedString( "flags", DBINFO( ply )[1][7] .. ",T" )
			XQAM_LOG( ply, ply:Nick() .. " received the T flag" )
		end
		
		DBUPDATE( ply, { "RANK= '" .. optrank .. "'", "FLAGS= '" .. ply:GetNetworkedString( "flags" ) .. "'" } )
		XQAM_LOG(ply, ply:Nick() .. " was promoted to " .. optrank )
		
	elseif optrank and !auto then
		APLY:SetNetworkedString( "rank", optrank )
		
		if RI >= tonumber(RankNums["Member"]) and string.find( APLY:GetNetworkedString( "flags" ), "T" ) == nil then
			APLY:SetNetworkedString( "flags", DBINFO( APLY )[1][7] .. ",T" )
			XQAM_LOG( APLY, APLY:Nick() .. " received the T flag" )
		end
		if RI >= tonumber(RankNums["Moderator"]) and string.find( APLY:GetNetworkedString( "flags" ), "M" ) == nil then
			APLY:SetNetworkedString( "flags", DBINFO( APLY )[1][7] .. ",M" )
			XQAM_LOG( APLY, APLY:Nick() .. " received the M flag" )
		end
		if RI >= tonumber(RankNums["Admin"]) and string.find( APLY:GetNetworkedString( "flags" ), "A" ) == nil then
			APLY:SetNetworkedString( "flags", DBINFO( APLY )[1][7] .. ",A" )
			XQAM_LOG( APLY, APLY:Nick() .. " received the A flag" )
		end
		if RI >= tonumber(RankNums["Owner"]) and string.find( APLY:GetNetworkedString( "flags" ), "O" ) == nil then
			APLY:SetNetworkedString( "flags", DBINFO( APLY )[1][7] .. ",O" )
			XQAM_LOG( APLY, APLY:Nick() .. " received the O flag" )
		end
		
		DBUPDATE( APLY, { "RANK= '" .. optrank .. "'", "FLAGS= '" .. APLY:GetNetworkedString( "flags" ) .. "'" } )
		XQAM_LOG(ply, " set " .. optrank .. " as the rank of " , APLY)
	end
	
end

function LogPLYConnect( name, address, steamid )
	XQAM_LOG(ply, name .. " connected from " .. address)
end
hook.Add("PlayerConnect", "LogConnect", LogPLYConnect)

function PLYSpawn( ply ) //Fix this to use the new DBINFO function
	local BanCheck = BanDBINFO( ply )
	
	if BanCheck[1] then
		if tonumber(os.time()) >= tonumber(BanCheck[1][5]) then
			BanDBDELETE( "", ply )
		else
			RunConsoleCommand( "kickid", ply:UserID(), "You are banned from this server." )
		end
	end
	

	XQAM_LOG(ply, ply:Nick() .. " spawned")
	ply:PrintMessage(HUD_PRINTTALK, string.format("Welcome to %s, enjoy your stay!", ServerName))
	ply:PrintMessage(HUD_PRINTCENTER, string.format("Welcome to %s, enjoy your stay!", ServerName))
	
	local CHECK = DBINFO( ply )
	
	if CHECK[1] and CHECK[1][2] then
		PrintTable( CHECK[1] )
		table.remove( CHECK[1], 1 )
		PrintTable( CHECK[1] )
		SetNWs( ply, CHECK[1] )
	else
		print( ply:Nick() .. " Failed the Check" )
		local NDATA = { ply:UniqueID(), ply:Nick(), "Beginner", 0, 0, "" }
		DBINSERT( ply, NDATA )
		SetNWs( ply, NDATA )
		
		ply:ConCommand( "ShowFirstHelp" )
	end
	
	
	
	//ply:ConCommand( "xqam_InitTables" )
	
end
hook.Add("PlayerInitialSpawn", "PLYSpawn", PLYSpawn)

function CheckFlags( ply, flag )
	local flags = ply:GetNetworkedString( "flags" )
	return string.find( flags, flag )
end

/*-------------------------------------------------------
Server Loggging
*/-------------------------------------------------------

function XQAM_LOG(ply, action, target)  //This is working fine, leave it for now.
	if(NumLog == -1) then
		NumLog = table.Count(file.Find("xqam/*.txt"))
	end
	
	if EnableDisplayLog and target then
		for k,v in pairs(player.GetAll()) do
			v:PrintMessage(HUD_PRINTTALK, ply:Nick() .. action .. target:Nick())
		end
	elseif EnableDisplayLog and target == nil then
		for k,v in pairs(player.GetAll()) do
			v:PrintMessage(HUD_PRINTTALK, action)
		end
	end
	
	if target then
		table.insert(LogTable,ply:Nick() .. action .. target:Nick())
	elseif target == nil then
		table.insert(LogTable,action)
	end
	
	local SafeOSString = string.Replace(os.date("%a %b %y"),"/","")
	SafeOSString = string.Replace(SafeOSString,":","")
	
	if (not file.IsDir("xqam")) then
		file.CreateDir("xqam")
	end
	
	if(table.Count(LogTable) < MaxLogTable) then
		file.Write("xqam/" .. SafeOSString .. NumLog .. ".txt",table.ToString(LogTable,"Logged Actions",true))
	elseif(table.Count(LogTable) >= MaxLogTable) then
		NumLog = NumLog + 1
		file.Write("xqam/" .. SafeOSString .. NumLog .. ".txt",table.ToString(LogTable,"Logged Actions",true))
		table.Empty(LogTable)
	end
	
end

function DC_HOOK( ply )
	TempTime[ply:UniqueID()] = nil
	XQAM_LOG(ply, ply:Nick() .. " disconnected")
end
hook.Add( "PlayerDisconnected", "DC_HOOK", DC_HOOK )

function NoClipHook( ply )
	if string.find(ply:GetNetworkedString( "flags" ), "N") then
		if !ply:GetNetworkedBool( "NoClip" ) then
			ply:PrintMessage(HUD_PRINTTALK, "Your NoClip abilities have been disabled" )
			return false
		end
	else
		ply:PrintMessage(HUD_PRINTTALK, "You lack the necessary flags to use NoClip" )
		return false
	end
end
hook.Add( "PlayerNoClip", "NoClipHook", NoClipHook )

function SavePlayerData( )
	for k,v in pairs( player.GetAll() ) do
		local DT = { "NAME= '" .. v:Nick() .. "'", "RANK= '" .. v:GetNetworkedString( "rank" ) .. "'", "TIME= " .. TempTime[v:UniqueID()], "POINTS= " .. v:GetNetworkedInt( "points" ), "FLAGS= '" .. v:GetNetworkedString( "flags" ) .. "'" }
		DBUPDATE( v, DT )
	end
end

function AdminMenuShow( ply )
	if string.find( ply:GetNetworkedString( "flags" ), "M" ) then
		ply:ConCommand( "ShowADMINMENU" )
	end
end
hook.Add("ShowSpare1", "AdminMenuShow", AdminMenuShow)

function InventoryMenuShow( ply )
	ply:ConCommand( "ShowInventory" )
end
hook.Add("ShowTeam", "InventoryMenuShow", InventoryMenuShow)

function SendTimes( ply, command, args )	//Work on this as well
	local rp = RecipientFilter()
	rp:AddPlayer( ply )
	Timez = ""
	
	for k,v in pairs(player.GetAll()) do
		Timez = Timez .. TempTime[v:UniqueID()] .. ":"
	end
	
	//umsg.PoolString( Timez )
	
	umsg.Start( "TMSG", rp )
		umsg.String( Timez )
	umsg.End()
end
concommand.Add( "xqam_SendTimes", SendTimes )

function SendSingleData( ply, command, args )
	local rp = RecipientFilter()
	local APLY = player.GetByUniqueID(args[1])
	rp:AddPlayer( ply )

	
	umsg.Start( "STMSG", rp )
		umsg.Long( TempTime[args[1]] )
		umsg.Entity( APLY )
	umsg.End()
end
concommand.Add( "xqam_SendSingleData", SendSingleData )